﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.OleDb;
using System.IO;

namespace Leiz.Tools.Z_Blog2WordPress
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 数据库链接字符串
        /// </summary>
        public const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};";

        /// <summary>
        /// 获取目录语句
        /// </summary>
        public const string SQL_GETCATEGORY = "select * from blog_Category";

        public const string COLUMNNAME_CATEGORY_CATENAEM = "cate_Name";

        /// <summary>
        /// 获取日志
        /// </summary>
        public const string SQL_GETARTICLE = "select a.log_ID as log_ID, a.log_Title as log_Title,a.log_Url as log_Url,a.log_PostTime as log_PostTime,a.log_Intro as log_Intro,a.log_Content as log_Content,m.mem_Name as log_Author,c.Cate_Name as log_Category from blog_Article a,blog_Member m,blog_Category  c where a.log_AuthorID = m.mem_ID and a.log_CateID = c.Cate_ID";
        public const string COLUMNNAME_BLOG_TITLE = "log_Title";
        public const string COLUMNNAME_BLOG_LINK = "log_Url";
        public const string COLUMNNAME_BLOG_POSTDATE = "log_PostTime";
        public const string COLUMNNAME_BLOG_INTRO = "log_Intro";
        public const string COLUMNNAME_BLOG_CONTENT = "log_Content";
        public const string COLUMNNAME_BLOG_AUTHOR = "log_Author";
        public const string COLUMNNAME_BLOG_CATEGORY = "log_Category";
        public const string COLUMNNAME_BLOG_ID = "log_ID";

        /// <summary>
        /// 获取评论
        /// </summary>
        public const string SQL_GETCOMMENT = "select * from blog_Comment where log_ID = {0}";

        public const string COLUMNNAME_COMMENT_ID = "comm_ID";
        public const string COLUMNNAME_COMMENT_AUTHOR = "comm_Author";
        public const string COLUMNNAME_COMMENT_EMAIL = "comm_Email";
        public const string COLUMNNAME_COMMENT_URL = "comm_HomePage";
        public const string COLUMNNAME_COMMENT_IP = "comm_IP";
        public const string COLUMNNAME_COMMENT_DATE = "comm_PostTime";
        public const string COLUMNNAME_COMMENT_CONTENT = "comm_Content";

        /// <summary>
        /// 链接
        /// </summary>
        private OleDbConnection m_connection = new OleDbConnection();

        public MainForm()
        {
            InitializeComponent();
        }

        private void buttonSelectData_Click(object sender, EventArgs e)
        {
            if (this.openFileDialogData.ShowDialog() == DialogResult.OK)
            {
                if (VerifyDataSchema(this.openFileDialogData.FileName))
                {
                    this.m_connection.ConnectionString = string.Format(CONNECTION_STRING, this.openFileDialogData.FileName);
                    this.buttonStart.Enabled = true;
                    this.groupBoxInput.Enabled = true;
                }
                else
                {
                    MessageBox.Show("数据库格式验证失败!", "错误", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 验证数据库格式
        /// </summary>
        /// <param name="path">数据文件路径</param>
        /// <returns>是否合适</returns>
        private bool VerifyDataSchema(string path)
        {
            return true;
        }

        private void GenerateXML()
        {
            if (this.saveFileDialogXML.ShowDialog() == DialogResult.OK)
            {
                XmlTextWriter xml = new XmlTextWriter(this.saveFileDialogXML.FileName, Encoding.UTF8);
                xml.Formatting = Formatting.Indented;
                xml.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                xml.WriteStartElement("rss");

                xml.WriteAttributeString("version", "2.0");
                xml.WriteAttributeString("xmlns", "content", null, "http://purl.org/rss/1.0/modules/content/");
                xml.WriteAttributeString("xmlns", "wfw", null, "http://wellformedweb.org/CommentAPI/");
                xml.WriteAttributeString("xmlns", "dc", null, "http://purl.org/dc/elements/1.1/");
                xml.WriteAttributeString("xmlns", "wp", null, "http://wordpress.org/export/1.0/");

                xml.WriteStartElement("channel");

                GenerateBlogDefinition(xml);
                GenerateCatalory(xml);
                GenerateItem(xml);

                xml.WriteEndElement();

                xml.WriteEndElement();
                xml.Close();
            }
        }

        /// <summary>
        /// 博客定义
        /// </summary>
        /// <param name="xml"></param>
        private void GenerateBlogDefinition(XmlTextWriter xml)
        {
            xml.WriteElementString("title", this.textBoxTitle.Text);
            xml.WriteElementString("link", this.textBoxURL.Text);
            xml.WriteElementString("description", this.textBoxDescription.Text);
            xml.WriteElementString("pubDate", DateTime.Now.ToString("R"));
            xml.WriteElementString("generator", "http://www.leiz.name");
            xml.WriteElementString("language", "zh-cn");
        }

        /// <summary>
        /// 文章分类
        /// </summary>
        /// <param name="xml"></param>
        private void GenerateCatalory(XmlTextWriter xml)
        {
            OleDbDataAdapter adapter = new OleDbDataAdapter(SQL_GETCATEGORY, this.m_connection);
            DataSet data = new DataSet();
            adapter.Fill(data);
            if (data.Tables.Count > 0)
            {
                foreach (DataRow dr in data.Tables[0].Rows)
                {
                    xml.WriteStartElement("wp", "category", null);
                    xml.WriteElementString("wp", "category_nicename", null, System.Web.HttpUtility.UrlEncode(Convert.ToString(dr[COLUMNNAME_CATEGORY_CATENAEM])));
                    xml.WriteElementString("wp", "category_parent", null, null);
                    xml.WriteElementString("wp", "posts_private", null, "0");
                    xml.WriteElementString("wp", "links_private", null, "0");

                    xml.WriteStartElement("wp", "cat_name", null);
                    xml.WriteCData(Convert.ToString(dr[COLUMNNAME_CATEGORY_CATENAEM]));
                    xml.WriteEndElement();

                    xml.WriteEndElement();
                }
            }
        }

        /// <summary>
        /// 文章
        /// </summary>
        /// <param name="xml"></param>
        private void GenerateItem(XmlTextWriter xml)
        {
            OleDbDataAdapter adapter = new OleDbDataAdapter(SQL_GETARTICLE, this.m_connection);
            DataSet data = new DataSet();
            adapter.Fill(data);
            if (data.Tables.Count > 0)
            {
                this.progressBarItem.Value = 0;
                this.progressBarItem.Maximum = data.Tables[0].Rows.Count;

                foreach (DataRow dr in data.Tables[0].Rows)
                {
                    xml.WriteStartElement("item");

                    xml.WriteElementString("title", Convert.ToString(dr[COLUMNNAME_BLOG_TITLE]));
                    xml.WriteElementString("link", Convert.ToString(dr[COLUMNNAME_BLOG_LINK]));
                    xml.WriteElementString("pubDate", Convert.ToDateTime(dr[COLUMNNAME_BLOG_POSTDATE]).ToString("R"));
                    xml.WriteElementString("dc", "creator", null, Convert.ToString(dr[COLUMNNAME_BLOG_AUTHOR]));

                    xml.WriteStartElement("category");
                    xml.WriteCData(Convert.ToString(dr[COLUMNNAME_BLOG_CATEGORY]));
                    xml.WriteEndElement();

                    xml.WriteStartElement("guid");
                    xml.WriteAttributeString("isPermaLink", "false");
                    xml.WriteString(Convert.ToString(dr[COLUMNNAME_BLOG_LINK]));
                    xml.WriteEndElement();

                    xml.WriteElementString("description", Convert.ToString(dr[COLUMNNAME_BLOG_INTRO]));

                    xml.WriteStartElement("content", "encoded", null);
                    xml.WriteCData(Convert.ToString(dr[COLUMNNAME_BLOG_CONTENT]));
                    xml.WriteEndElement();

                    xml.WriteElementString("wp", "post_id", null, Convert.ToString(dr[COLUMNNAME_BLOG_ID]));
                    xml.WriteElementString("wp", "post_date", null, Convert.ToDateTime(dr[COLUMNNAME_BLOG_POSTDATE]).ToString("yyyy-MM-dd HH:mm:ss"));
                    xml.WriteElementString("wp", "post_date_gmt", null, Convert.ToDateTime(dr[COLUMNNAME_BLOG_POSTDATE]).ToString("yyyy-MM-dd HH:mm:ss"));
                    xml.WriteElementString("wp", "comment_status", null, "open");
                    xml.WriteElementString("wp", "ping_status", null, "open");
                    xml.WriteElementString("wp", "post_name", null, string.Empty);
                    xml.WriteElementString("wp", "status", null, "publish");
                    xml.WriteElementString("wp", "post_parent", null, "0");
                    xml.WriteElementString("wp", "menu_order", null, "0");
                    xml.WriteElementString("wp", "post_type", null, "post");

                    GenerateComment(xml, Convert.ToString(dr[COLUMNNAME_BLOG_ID]));

                    xml.WriteEndElement();

                    this.progressBarItem.Value++;
                }
            }
        }

        /// <summary>
        /// 生成留言
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="articleID"></param>
        private void GenerateComment(XmlTextWriter xml, string articleID)
        {
            OleDbDataAdapter adapter = new OleDbDataAdapter(string.Format(SQL_GETCOMMENT, articleID), this.m_connection);
            DataSet data = new DataSet();
            adapter.Fill(data);
            if (data.Tables.Count > 0)
            {
                foreach (DataRow dr in data.Tables[0].Rows)
                {
                    xml.WriteStartElement("wp", "comment", null);

                    xml.WriteElementString("wp", "comment_id", null, Convert.ToString(dr[COLUMNNAME_COMMENT_ID]));
                    xml.WriteElementString("wp", "comment_author", null, Convert.ToString(dr[COLUMNNAME_COMMENT_AUTHOR]));
                    xml.WriteElementString("wp", "comment_author_email", null, Convert.ToString(dr[COLUMNNAME_COMMENT_EMAIL]));
                    xml.WriteElementString("wp", "comment_author_url", null, Convert.ToString(dr[COLUMNNAME_COMMENT_URL]));
                    xml.WriteElementString("wp", "comment_author_IP", null, Convert.ToString(dr[COLUMNNAME_COMMENT_IP]));
                    xml.WriteElementString("wp", "comment_date", null, Convert.ToDateTime(dr[COLUMNNAME_COMMENT_DATE]).ToString("yyyy-MM-dd HH:mm:ss"));
                    xml.WriteElementString("wp", "comment_date_gmt", null, Convert.ToDateTime(dr[COLUMNNAME_COMMENT_DATE]).ToString("yyyy-MM-dd HH:mm:ss"));
                    xml.WriteElementString("wp", "comment_content", null, Convert.ToString(dr[COLUMNNAME_COMMENT_CONTENT]));
                    xml.WriteElementString("wp", "comment_approved", null, "1");
                    xml.WriteElementString("wp", "comment_type", null, string.Empty);
                    xml.WriteElementString("wp", "comment_parent", null, "0");

                    xml.WriteEndElement();
                }
            }
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            GenerateXML();
            MessageBox.Show("转换完成!", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private void linkLabelURL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(this.linkLabelURL.Text);
        }
    }
}